<?php

declare(strict_types=1);

namespace app\common\model;

use think\facade\Db;
use app\common\tool\excel\Export;

class Precept extends Base
{

    protected $name = 'precept';

    protected $type = [
        'hand_time'    => 'timestamp',
        'finish_time'    => 'timestamp',
    ];
    public function admin()
    {
        return $this->hasOne(Admin::class, 'id', 'admin_id')->field('id,admin_name as code,comment as nickname,mobile,role_id')->with(['level']);
    }
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,photo,mobile,level_id,job')->with(['level']);
    }
    public function huser()
    {
        return $this->hasOne(User::class, 'id', 'h_id')->field('id,code,nickname,photo,mobile,level_id,level_id,job')->with(['level']);
    }
    public function tuser()
    {
        return $this->hasOne(User::class, 'id', 't_id')->field('id,code,nickname,photo,mobile,level_id,level_id,job')->with(['level']);
    }

    public function getStatusTextAttr($value, $data)
    {
        return self::getStatus($data['status']);
    }
    public static function getStatus($value, $type = 1)
    {
        $status = [1 => '已认领', 2 => '待处理', 3 => '处理中', 4 => '待支付', 5 => '待评价', 6 => '已完成'];
        return $type == 1 ? $status[$value] : $status;
    }
    public static function getStatusList($admin_id = 1)
    {
        $list = [
            [
                'id' => 1,
                'title' => '已认领',
            ],
            [
                'id' => 2,
                'title' => '待处理',
            ],
            [
                'id' => 3,
                'title' => '处理中',
            ],
            [
                'id' => 4,
                'title' => '待支付',
            ],
            [
                'id' => 5,
                'title' => '待评价',
            ],
            [
                'id' => 6,
                'title' => '已完成',
            ]
        ];
        if ($admin_id != 1) {
            $map[] = ['admin_id', '=', $admin_id];
        }
        $map[] = ['id', '>', 0];
        foreach ($list as &$v) {
            $v['count'] = parent::where('status', $v['id'])->where($map)->count();
        }
        return $list;
    }
    public function getTypeTextAttr($value, $data)
    {
        return self::getType($data['type']);
    }
    public static function getType($value, $type = 1)
    {
        $status = [1 => '个人需求', 2 => '家庭需求', 3 => '单位需求', 4 => '其他需求'];
        return $type == 1 ? $status[$value] : $status;
    }

    public function getTypeTitleAttr($value, $data)
    {
        return self::getTypeTitle($data['type']);
    }
    public static function getTypeTitle($value, $type = 1)
    {
        $status = [1 => '个人', 2 => '家庭', 3 => '单位', 4 => '其他'];
        return $type == 1 ? $status[$value] : $status;
    }

    public static function getTypeList()
    {
        $list = [
            [
                'id' => 1,
                'title' => '个人需求',
                'sub_title' => '个人',
            ],
            [
                'id' => 2,
                'title' => '家庭需求',
                'sub_title' => '家庭',
            ],
            [
                'id' => 3,
                'title' => '单位需求',
                'sub_title' => '单位',
            ],
            [
                'id' => 4,
                'title' => '其他需求',
                'sub_title' => '其他'
            ]
        ];
        return $list;
    }
       /**
     * 数据
     */
    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            if (isset($param['export']) && $param['export']==1) {
                $datalist = [];
                $PreceptEvaluate = PreceptEvaluate::getComment();
                foreach ($that as $key => $v) {
                    $datainfo =[
                        $v->sn,
                        $v->rname,
                        $v->tel,
                        $v->typeText,
                        !empty($v->user)?$v->user->nickname.'-'.$v->user->code.'-'.$v->user->mobile:"",
                        !empty($v->admin)?$v->admin->nickname.'-'.$v->admin->code.'-'.$v->admin->mobile:"",
                        !empty($v->huser)?$v->huser->nickname.'-'.$v->huser->code.'-'.$v->huser->mobile:"",
                        !empty($v->tuser)?$v->tuser->nickname.'-'.$v->tuser->code.'-'.$v->tuser->mobile:"",
                        $v->statusText,
                    ];
                    $evaluate_id = array_column($PreceptEvaluate,'id');
                    $elist = [];
                    foreach($evaluate_id as &$ev){
                        $einfo = PreceptEvaluate::where(['precept_id'=>$v->id])->find();
                        if(empty($einfo)){
                            $eval = '';
                        }else{
                            $eval = $einfo['score_'.$ev].'分';
                        }
                        $elist[] = $eval;
                    }
                    $datalist[] = array_merge($datainfo,$elist);
                }
                $datatitle = [
                    '方案编号',
                    '姓名',
                    '电话',
                    '需求类型',
                    '方案用户',
                    '运营经理',
                    '健康师',
                    '专家/服务团队',
                    '状态'
                ];
                if (count($that) > 0) {
                    return ['code' => 0, 'data' => Export::export(array_merge($datatitle,array_column($PreceptEvaluate,'title')), $datalist, "uploads/file/方案评价.xlsx")];
                } else {
                    return ['code' => 0, 'data' => 0];
                }
            }
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }
    /**
     * 添加方案
     */
    public static function add($param, $user)
    {
        parent::startTrans();
        try {
            $admin = Admin::where(['role_id' => 9, 'status' => 1])->orderRaw('rand()')->find();
            if (empty($admin)) {
                return ['code' => -1, 'msg' => '暂无运营经理'];
            }
            if ($user->level_id != 1) {
                return ['code' => -1, 'msg' => '该身份不可认领健康管理师！'];
            }
            $info = parent::where('uid', $user->id)->where('create_time', '>=', (time() - 30))->find();
            if ($info) {
                return ['code' => -1, 'msg' => '操作太快，请稍后再试'];
            }
            $h_info = Expert::where(['uid' => $param['h_id'], 'type' => 2])->find();
            if (empty($h_info)) {
                return ['code' => -1, 'msg' => '健康管理师不存在'];
            }
            $param['admin_id'] = $admin->id;
            $param['uid'] = $user->id;
            $param['sn'] = 'P' . date('YmdHis') . $user->id . rand(100000, 999999);
            $news = parent::create($param);
            PreceptLog::adds($news->id, $user->id, '认领方案填写成功', '恭喜您认领成功，请您耐心等待运营经理处理方案');
            PreceptLog::adds($news->id, $param['h_id'], '认领方案', $user->nickname . '填写了方案！请您跟踪处理方案');
            parent::commit();
            return ['code' => 1, 'msg' => '认领成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 选择专家
     */
    public static function preceptAllot($param, $admin)
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '方案不存在'];
            }
            $user = User::where('id', $param['t_id'])->where('level_id', '>=', 3)->find();
            if (empty($user)) {
                return ['code' => -1, 'msg' => '专家/服务团队不存在'];
            }
            if ($info['status'] != 1) {
                return ['code' => -1, 'msg' => '方案状态不正确'];
            }
            $info->status = 2;
            $info->t_id = $param['t_id'];
            $info->over_time = time() + 86400;
            $info->save();
            PreceptLog::adds($info->id, $info->uid, '方案分配', '方案已分配到' . $user->level->title . '【' . $user->nickname . '】');
            PreceptLog::adds($info->id, $param['t_id'], '方案分配', '方案已分配给您！请您跟踪处理方案');
            Logs::adds('方案已分配，方案ID【' . $param['id'] . '】' . $user->level->title . '【' . $user->nickname . '】', $admin->id, $admin->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => '方案已分配'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 填写方案
     */
    public static function edit($param, $user)
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '方案不存在'];
            }
            if ($info['status'] != 2) {
                return ['code' => -1, 'msg' => '方案状态不正确'];
            }
            if ($info->t_id != $user->id) {
                return ['code' => -1, 'msg' => '非本人的方案！不可处理'];
            }
            $msg = empty($info->precept_reject) ? '方案填写成功' : '方案修改成功';
            $info->status = 3;
            $info->precept_title = $param['precept_title'];
            $info->precept_images = $param['precept_images'];
            $info->precept_note = $param['precept_note'];
            $info->precept_reject = '';
            $info->hand_time = time();
            $info->save();
            return ['code' => 1, 'msg' => $msg];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 方案报价
     */
    public static function preceptOffer($param, $admin)
    {
        parent::startTrans();
        try {
            if (!isset($param['audit'])) return ['code' => -1, 'msg' => '请选择审核类型'];
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '方案不存在'];
            }
            if ($info['status'] != 3) {
                return ['code' => -1, 'msg' => '方案状态不正确'];
            }
            if ($param['audit'] == 1) {
                $info->status = 4;
                $info->reject_msg = '';
                $info->precept_reject = '';
                $info->price = $param['price'];
                PreceptLog::adds($info->id, $info->uid, '方案报价', '运营经理已给出了报价！请您到我的方案进行支付！');
                $logs = '方案报价通过';
                $msg = $logs;
            } else {
                $info->price = '';
                $info->reject_msg = $param['reject_msg'];
                $info->status = 2;
                $info->precept_title = '';
                $info->precept_images = '';
                $info->precept_note = '';
                PreceptLog::adds($info->id, $info->t_id, '方案驳回', '您的放方案被驳回，请修改后重新修改方案！');
                $logs = '方案驳回';
                $msg = $logs . '成功！';
            }
            $info->save();
            Logs::adds($logs . '，方案ID【' . $param['id'] . '】', $admin->id, $admin->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => $msg];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 方案用户驳回
     */
    public static function reject($param, $user)
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '方案不存在'];
            }
            if ($info['status'] != 4) {
                return ['code' => -1, 'msg' => '方案状态不正确'];
            }
            $info->status = 3;
            $info->precept_reject = $param['precept_reject'];
            $info->save();
            parent::commit();
            return ['code' => 1, 'msg' => '驳回成功！'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 方案24小时未处理
     */
    public static function release()
    {
        parent::startTrans();
        try {
            $list = parent::where('status', 2)->where('over_time', '<', time())->where('over_time','<>',0)->select();
            if ($list->isEmpty()) {
                return ['code' => -1, 'msg' => '暂无超时未处理的方案！'];
            }
            foreach ($list as $k => $v) {
                $v->status = 1;
                $v->over_time = 0;
                PreceptLog::adds($v->id, $v->t_id, '方案超时', '方案已超时未处理，系统重新分配！');
                $v->t_id=0;
                PreceptLog::adds($v->id, $v->uid, '方案超时', '方案已超时未处理，系统重新分配！');
                $v->save();
            }
            return ['code' => 1, 'msg' => '处理成功！'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
